package com.clhbolg.strategy.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.clhbolg.properties.OssConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @Author cailinhu
 * @Description aliyun OSS文件上传器
 * @Date 2023/2/8 10:20
 * @Version 1.0
 */
@Service
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl{
    @Autowired
    private OssConfigProperties ossConfigProperties;


    @Override
    public Boolean exists(String filePath) {
        return getOssClient().doesObjectExist(ossConfigProperties.getBucketName(), filePath);
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        getOssClient().putObject(ossConfigProperties.getBucketName(), path + fileName, inputStream);
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        return ossConfigProperties.getUrl() + filePath;
    }

    @Override
    public void deleteFile(String fileName) {
        OSS ossClient = getOssClient();
        if (StrUtil.isNotEmpty(fileName)){
            if (exists(fileName)) {
                ossClient.deleteObject(ossConfigProperties.getBucketName(),fileName);
            }
        }
    }

    private OSS getOssClient() {
        return new OSSClientBuilder().build(ossConfigProperties.getEndpoint(), ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
    }
}
